#
# battle.py -- battle arena
# 
# author: Tom "Knio" Flanagan
#         knio@h4xn3t.net
#         theknio@gmail.com
#         irc.freenode.net - Knio - #python #pygame #py
#
# this file released under Public Domain
#


from constants import *
import ship
        
        
class Battle:
    def __init__(self, **kwargs):
        self.objects = {}
        self.distances = {}
        
        self.size = 100
        self.friction = 1000.
        self.done = 0
        self.turn = 0
        self.__dict__.update(kwargs)

    def add(self, object):
        for i in self.objects:
            o1 = (object>i and i) or object
            o2 = (object<i and i) or object
            pair = (o1, o2)
            self.distances[pair] = [object.distance(i)]

        for i in self.objects:
            self.objects[i].append((self.distance(object, i), object))
            self.objects[i].sort()

        self.objects[object] = [(self.distance(object, key), key) for key in self.objects.keys()]
        self.objects[object].sort()
        
    def remove(self, object):
        del self.objects[object]
        for i in self.objects:
            o1 = (object>i and i) or object
            o2 = (object<i and i) or object
            pair = (o1, o2)
            del self.distances[pair]

    def distance(self, object1, object2):
        o1 = (object1>object2 and object2) or object1
        o2 = (object1<object2 and object2) or object1
        pair = (o1, o2)
        return self.distances[pair]
        
    def update(self):
        for i in self.distances:
            self.distances[i][0] = i[0].distance(i[1])

        for i in self.objects:
            self.objects[i].sort()        
        
    def tick(self):
        self.turn += 1
        if not self.objects:
            self.done = 1
            return self.done

        for i in self.objects.keys():  i.tick(self.objects[i][:])
        for i in self.objects.keys():  i.move()
        if not (self.turn % 30): self.update()
                    
        t = len(dict([(i.team, None) for i in self.objects if isinstance(i, ship.Ship) and i.state]))
        if t == 1:  self.done = 1
        

